<template>
  <el-dialog
    :model-value="visible"
    :title="isEdit ? '编辑场馆' : '新增场馆'"
    width="800px"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      @submit.prevent
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="场馆名称" prop="name">
            <el-input
              v-model="formData.name"
              placeholder="请输入场馆名称"
              maxlength="100"
              show-word-limit
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="状态" prop="status">
            <el-select v-model="formData.status" placeholder="选择状态" style="width: 100%">
              <el-option label="活跃" value="ACTIVE" />
              <el-option label="停用" value="INACTIVE" />
              <el-option label="维护中" value="MAINTENANCE" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="城市" prop="city">
            <el-input
              v-model="formData.city"
              placeholder="请输入城市"
              maxlength="50"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="国家" prop="country">
            <el-input
              v-model="formData.country"
              placeholder="请输入国家"
              maxlength="50"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="场馆地址" prop="address">
        <el-input
          v-model="formData.address"
          placeholder="请输入场馆地址"
          maxlength="200"
          show-word-limit
        />
      </el-form-item>

      <el-form-item label="场馆描述" prop="description">
        <el-input
          v-model="formData.description"
          type="textarea"
          :rows="3"
          placeholder="请输入场馆描述"
          maxlength="65535"
          show-word-limit
        />
      </el-form-item>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="场馆容量" prop="capacity">
            <el-input-number
              v-model="formData.capacity"
              :min="1"
              :max="999999"
              placeholder="请输入容量"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="排序优先级" prop="sortOrder">
            <el-input-number
              v-model="formData.sortOrder"
              :min="0"
              :max="999999"
              placeholder="数字越小排序越靠前"
              style="width: 100%"
            />
            <div class="field-tip">数字越小排序越靠前，建议使用 0-100 之间的数值</div>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="联系电话" prop="contactPhone">
            <el-input
              v-model="formData.contactPhone"
              placeholder="请输入联系电话"
              maxlength="20"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系邮箱" prop="contactEmail">
            <el-input
              v-model="formData.contactEmail"
              placeholder="请输入联系邮箱"
              maxlength="100"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="网站地址" prop="website">
            <el-input
              v-model="formData.website"
              placeholder="请输入网站地址"
              maxlength="200"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="纬度" prop="latitude">
            <el-input
              v-model="formData.latitude"
              placeholder="请输入纬度 (-90 到 90)"
              type="number"
              :step="0.001"
              :min="-90"
              :max="90"
            />
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="经度" prop="longitude">
            <el-input
              v-model="formData.longitude"
              placeholder="请输入经度 (-180 到 180)"
              type="number"
              :step="0.001"
              :min="-180"
              :max="180"
            />
          </el-form-item>
        </el-col>
      </el-row>
      
      <!-- 地图选择器 -->
      <el-form-item label="地图选择位置">
        <div class="map-selector">
          <div class="map-container" ref="mapContainer">
            <div class="map-placeholder" v-if="!mapLoaded">
              <el-icon><Location /></el-icon>
              <span>点击加载地图预览</span>
              <el-button type="primary" size="small" @click="loadMap" style="margin-left: 10px">
                加载地图
              </el-button>
            </div>
            <div id="map" v-show="mapLoaded" class="map"></div>
          </div>
          <div class="map-controls">
            <el-button type="primary" size="small" @click="useCurrentLocation">
              <el-icon><Location /></el-icon>
              使用当前位置
            </el-button>
            <el-button type="info" size="small" @click="clearLocation">
              清除位置
            </el-button>
            <el-button type="success" size="small" @click="openMapPicker">
              <el-icon><Location /></el-icon>
              在地图中选择
            </el-button>
          </div>
        </div>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          {{ isEdit ? '更新' : '创建' }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch, nextTick } from 'vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { Location } from '@element-plus/icons-vue'
import type { VenueData } from '@/api/venue'
import { createVenue, updateVenue } from '@/api/venue'



// Props
interface Props {
  visible: boolean
  venueData: VenueData | null
  isEdit: boolean
}

const props = defineProps<Props>()

// Emits
const emit = defineEmits<{
  'update:visible': [value: boolean]
  'success': []
}>()

// 响应式数据
const formRef = ref<FormInstance>()
const submitting = ref(false)
const mapContainer = ref<HTMLElement>()
const mapLoaded = ref(false)

// 表单数据
const formData = reactive<Omit<VenueData, 'id' | 'createdAt' | 'updatedAt'>>({
  name: '',
  description: '',
  address: '',
  city: '',
  country: '',
  capacity: undefined,
  sortOrder: 0,
  contactPhone: '',
  contactEmail: '',
  website: '',
  latitude: undefined,
  longitude: undefined,
  status: 'ACTIVE'
})

// 表单验证规则
const formRules: FormRules = {
  name: [
    { required: true, message: '请输入场馆名称', trigger: 'blur' },
    { min: 1, max: 100, message: '场馆名称长度在 1 到 100 个字符', trigger: 'blur' }
  ],
  address: [
    { required: true, message: '请输入场馆地址', trigger: 'blur' },
    { min: 1, max: 200, message: '场馆地址长度在 1 到 200 个字符', trigger: 'blur' }
  ],
  city: [
    { required: true, message: '请输入城市', trigger: 'blur' },
    { min: 1, max: 50, message: '城市名称长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  country: [
    { required: true, message: '请输入国家', trigger: 'blur' },
    { min: 1, max: 50, message: '国家名称长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  capacity: [
    { type: 'number', min: 1, message: '场馆容量必须大于0', trigger: 'blur' }
  ],
  sortOrder: [
    { type: 'number', min: 0, message: '排序值必须大于等于0', trigger: 'blur' }
  ],
  contactPhone: [
    { pattern: /^[\+]?[1-9][\d]{0,15}$/, message: '请输入正确的联系电话格式', trigger: 'blur' }
  ],
  contactEmail: [
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  website: [
    { pattern: /^https?:\/\/.+/, message: '网站地址必须以http://或https://开头', trigger: 'blur' }
  ],
  latitude: [
    { 
      validator: (rule: any, value: any, callback: any) => {
        if (value === '' || value === null || value === undefined) {
          callback()
        } else {
          const num = Number(value)
          if (isNaN(num)) {
            callback(new Error('纬度必须是数字'))
          } else if (num < -90 || num > 90) {
            callback(new Error('纬度必须在-90到90之间'))
          } else {
            callback()
          }
        }
      },
      trigger: 'blur'
    }
  ],
  longitude: [
    { 
      validator: (rule: any, value: any, callback: any) => {
        if (value === '' || value === null || value === undefined) {
          callback()
        } else {
          const num = Number(value)
          if (isNaN(num)) {
            callback(new Error('经度必须是数字'))
          } else if (num < -180 || num > 180) {
            callback(new Error('经度必须在-180到180之间'))
          } else {
            callback()
          }
        }
      },
      trigger: 'blur'
    }
  ]
}

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    name: '',
    description: '',
    address: '',
    city: '',
    country: '',
    capacity: undefined,
    sortOrder: 0,
    contactPhone: '',
    contactEmail: '',
    website: '',
    latitude: undefined,
    longitude: undefined,
    status: 'ACTIVE'
  })
  
  // 清除验证错误
  nextTick(() => {
    formRef.value?.clearValidate()
  })
}

// 监听场馆数据变化
watch(
  () => props.venueData,
  (newData) => {
    if (newData) {
      // 编辑模式，填充表单数据
      Object.assign(formData, {
        name: newData.name || '',
        description: newData.description || '',
        address: newData.address || '',
        city: newData.city || '',
        country: newData.country || '',
        capacity: newData.capacity || undefined,
        sortOrder: newData.sortOrder || 0,
        contactPhone: newData.contactPhone || '',
        contactEmail: newData.contactEmail || '',
        website: newData.website || '',
        latitude: newData.latitude || undefined,
        longitude: newData.longitude || undefined,
        status: newData.status || 'ACTIVE'
      })
    } else {
      // 新增模式，重置表单数据
      resetForm()
    }
  },
  { immediate: true }
)

// 关闭对话框
const handleClose = () => {
  emit('update:visible', false)
  resetForm()
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitting.value = true
    
    if (props.isEdit && props.venueData?.id) {
      // 编辑模式
      const response = await updateVenue(props.venueData.id, formData)
      if (response.success) {
        ElMessage.success('更新场馆成功')
        emit('success')
      } else {
        ElMessage.error(response.message || '更新场馆失败')
      }
    } else {
      // 新增模式
      const response = await createVenue(formData)
      if (response.success) {
        ElMessage.success('创建场馆成功')
        emit('success')
      } else {
        ElMessage.error(response.message || '创建场馆失败')
      }
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('提交表单失败:', error)
      ElMessage.error(props.isEdit ? '更新场馆失败' : '创建场馆失败')
    }
  } finally {
    submitting.value = false
  }
}

// 地图相关函数
const loadMap = () => {
  // 使用 OpenStreetMap (免费，无需API密钥)
  const defaultLat = formData.latitude ? Number(formData.latitude) : 39.9042
  const defaultLng = formData.longitude ? Number(formData.longitude) : 116.4074
  
  const mapElement = document.getElementById('map')
  if (!mapElement) return
  
  // 创建地图容器
  mapElement.innerHTML = `
    <iframe 
      src="https://www.openstreetmap.org/export/embed.html?bbox=${defaultLng-0.01},${defaultLat-0.01},${defaultLng+0.01},${defaultLat+0.01}&layer=mapnik&marker=${defaultLat},${defaultLng}"
      width="100%" 
      height="300" 
      frameborder="0" 
      scrolling="no" 
      marginheight="0" 
      marginwidth="0"
      title="OpenStreetMap"
    ></iframe>
  `
  
  mapLoaded.value = true
  ElMessage.success('地图加载成功，点击下方按钮选择位置')
}

const useCurrentLocation = () => {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(
      (position) => {
        const lat = position.coords.latitude
        const lng = position.coords.longitude
        
        formData.latitude = lat
        formData.longitude = lng
        
        // 重新加载地图以显示新位置
        if (mapLoaded.value) {
          loadMap()
        }
        
        ElMessage.success('已获取当前位置')
      },
      (error) => {
        console.error('获取位置失败:', error)
        ElMessage.error('获取当前位置失败，请手动选择位置')
      }
    )
  } else {
    ElMessage.error('浏览器不支持地理位置功能')
  }
}

const clearLocation = () => {
  formData.latitude = undefined
  formData.longitude = undefined
  
  // 重新加载地图以清除标记
  if (mapLoaded.value) {
    loadMap()
  }
  
  ElMessage.success('已清除位置信息')
}

const openMapPicker = () => {
  // 打开新窗口让用户在地图中选择位置
  const currentLat = formData.latitude || 39.9042
  const currentLng = formData.longitude || 116.4074
  
  const mapUrl = `https://www.openstreetmap.org/?mlat=${currentLat}&mlon=${currentLng}#map=13/${currentLat}/${currentLng}`
  const newWindow = window.open(mapUrl, '_blank', 'width=1200,height=800')
  
  if (newWindow) {
    ElMessage.info('已打开地图选择器，请在地图中选择位置后复制坐标到表单中')
  } else {
    ElMessage.error('无法打开地图选择器，请检查浏览器弹窗设置')
  }
}

// 监听经纬度变化，同步地图显示
watch(
  () => [formData.latitude, formData.longitude],
  ([lat, lng]) => {
    // 如果地图已加载且有新的坐标，重新加载地图
    if (mapLoaded.value && lat && lng) {
      loadMap()
    }
  }
)
</script>

<style scoped lang="scss">
.dialog-footer {
  text-align: right;
}

:deep(.el-form-item__content) {
  .el-input-number {
    width: 100%;
  }
}

.map-selector {
  .map-container {
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    overflow: hidden;
    margin-bottom: 10px;
    
    .map-placeholder {
      display: flex;
      align-items: center;
      justify-content: center;
      height: 300px;
      background-color: #f5f7fa;
      color: #909399;
      
      .el-icon {
        margin-right: 8px;
        font-size: 20px;
      }
    }
    
    .map {
      width: 100%;
      height: 300px;
    }
  }
  
  .map-controls {
    display: flex;
    gap: 10px;
    margin-top: 10px;
  }

  .field-tip {
    font-size: 12px;
    color: #909399;
    margin-top: 4px;
    line-height: 1.4;
  }
}
</style>
